﻿
using System;
using System.Collections.Generic;

using Irony.Compiler;

namespace IronLua.Ast {

	public class FunctionCallExpression : Expression {

		readonly Expression target;
		readonly ExpressionList arguments = new ExpressionList ();

		public Expression Target {
			get { return target; }
		}

		public ExpressionList Arguments {
			get { return arguments; }
		}

		public override LuaNodeType NodeType {
			get { return LuaNodeType.FunctionCallExpression; }
		}

		public FunctionCallExpression (CompilerContext context, NonTerminal nonTerminal, SourceLocation location, AstNodeList childNodes)
			: base (context, nonTerminal, location, childNodes)
		{
			target = ChildNodes [0].ToExpression ();
			var args = ChildNodes [ChildNodes.Count - 1];
			if (args.ChildNodes.Count > 0)
				arguments.AddRange (CollectArguments ());
		}

		IEnumerable<Expression> CollectArguments ()
		{
			return CollectionExpressionList (ChildNodes [ChildNodes.Count - 1].ChildNodes [0]);
		}

		IEnumerable<Expression> CollectionExpressionList (AstNode list)
		{
			foreach (var node in list.ChildNodes [0].ChildNodes)
				yield return node.ChildNodes [0].ToExpression ();

			if (list.ChildNodes.Count > 1 && list.ChildNodes [1] != null)
				yield return list.ChildNodes [1].ToExpression ();
		}

		public override void Accept (ILuaAstVisitor visitor)
		{
			visitor.VisitFunctionCallExpression (this);
		}
	}
}
